05. DB Testing

JavaND#305 C03 L02 A05 DB Testing

Spring Data JPA Tests

To test Spring Data JPA repositories, or any other JPA-related components for that matter, Spring Boot provides the @DataJpaTest annotation. We can just add it to our JUnit tests and it will set up a Spring application context.

Let’s see how to write a JUnit 4 test for our OrderRepository,

@RunWith(SpringRunner.class)
@DataJpaTest
public class OrderRepositoryTest {

  @Autowired private DataSource dataSource;
  @Autowired private JdbcTemplate jdbcTemplate;
  @Autowired private EntityManager entityManager;
  @Autowired private TestEntityManager testEntityManager;
  @Autowired private OrderRepository orderRepository;

  @Test
  public void injectedComponentsAreNotNull(){
    assertThat(dataSource).isNotNull();
    assertThat(jdbcTemplate).isNotNull();
    assertThat(entityManager).isNotNull();
    assertThat(testEntityManager).isNotNull();
    assertThat(orderRepository).isNotNull();
  }

  @Test
  public void testFindByCustomerName(){
     // create Order
     Order order = new Order();
     // set fields
    order.setCustomerName(“John Doe”);
    …

    entityManager.persist(order);

    Order actual = orderRepository.findByCustomerName(“John Doe”)
    assertThat(actual).isNotNull();
    assertEquals(order.getId(), actual.getId());
  }
}

The so created application context will not contain the whole context needed for our Spring Boot application, but instead only a “slice” of it containing the components needed to initialize any JPA-related components like our Spring Data repository.

We can, for instance, inject a DataSource, JdbcTemplate, EntityManager or a specialized wrapper TestEntityManager with helper methods for testing, into our test class if we need them. Also, we can inject any of the Spring Data repositories from our application. All of the above components will be automatically configured to point to an embedded, in-memory database instead of the “real” database we might have configured in application.properties files.

Note that by default the application context containing all these components, including the in-memory database, is shared between all test methods within all @DataJpaTest-annotated test classes.
This is why, by default, each test method runs in its own transaction, which is rolled back after the method has executed. This way, the database state stays pristine between tests and the tests stay independent of each other.

Resources

Exercise

Task Description:

Students will write tests for some of the operations done in the previous exercises.

Task List:

Task Feedback:

Nice job on writing tests.